import { ref } from 'vue'

export function usePlacing(canvas) {
    const isPlacing = ref(false)
    const placingType = ref(null)
    const placingDevice = ref(null)

    const startPlacing = (type, device = null) => {
        isPlacing.value = true
        placingType.value = type
        placingDevice.value = device
        canvas.defaultCursor = 'crosshair'
        canvas.selection = false
        canvas.forEachObject(obj => {
            obj.selectable = false
        })
    }

    const exitPlacingMode = () => {
        isPlacing.value = false;
        placingType.value = null;
        placingDevice.value = null;
        canvas.defaultCursor = 'default';
        canvas.selection = true;
        canvas.forEachObject(obj => {
            obj.selectable = true;
        });
    };

    const placeRect = (pointer) => {
        const rect = new fabric.Rect({
            left: pointer.x - 80,
            top: pointer.y - 75,
            fill: '#f4f4f4',
            stroke: '#000000',
            strokeWidth: 1,
            width: 160,
            height: 150,
            selectable: true,
            zIndex: 1  // 设置为最低层级
        })
        canvas.add(rect)
        // 确保矩形在最底层
        canvas.sendToBack(rect)
        canvas.renderAll()
    }

    const placeCircle = (pointer) => {
        const circle = new fabric.Circle({
            left: pointer.x - 25,
            top: pointer.y - 25,
            fill: '#f4f4f4',
            stroke: '#000000',
            strokeWidth: 1,
            radius: 25,
            selectable: true,
            zIndex: 2  // 设置为比矩形高一层
        })
        canvas.add(circle)
        // 将圆形放在所有矩形之上，但在其他元素之下
        canvas.bringForward(circle)
        canvas.renderAll()
    }

    const placeText = (pointer) => {
        const text = new fabric.IText('双击编辑文字', {
            left: pointer.x,
            top: pointer.y,
            fontSize: 12,
            fill: '#000',
            editable: true,
            selectable: true
        })
        canvas.add(text)
        canvas.setActiveObject(text)
    }

    const placeDevice = (pointer) => {
        if (!placingDevice.value) return
        console.log('load svg content:', placingDevice.value);

        const svgPath = placingDevice.value.svgPath
        const subDevice = placingDevice.value.subDevice
        fetch(svgPath)
            .then(response => response.text())
            .then(svgContent => {
                fabric.loadSVGFromString(svgContent, (objects, options) => {
                    const svgGroup = fabric.util.groupSVGElements(objects, options)
                    svgGroup.set({
                        left: pointer.x - (svgGroup.width * 0.5 * 0.5),
                        top: pointer.y - (svgGroup.height * 0.5 * 0.5),
                        scaleX: 0.5,
                        scaleY: 0.5,
                        selectable: true,
                        deviceInfo: subDevice,
                    })
                    canvas.add(svgGroup)
                    canvas.setActiveObject(svgGroup)
                    canvas.requestRenderAll()
                })
            })
            .catch(error => {
                console.error('加载 SVG 失败:', error)
            })
    }

    const performPlacement = (pointer) => {
        console.log('performPlacement', pointer, placingType.value);
        if (!isPlacing.value) return
        switch (placingType.value) {
            case 'rect':
                placeRect(pointer)
                break
            case 'circle':
                placeCircle(pointer)
                break
            case 'text':
                placeText(pointer)
                break
            case 'device':
                placeDevice(pointer)
                break
            default:
                console.warn('未处理的放置类型:', placingType.value)
        }
        // 放置完成后退出放置模式
        exitPlacingMode()
    }

    return {
        isPlacing,
        placingType,
        placingDevice,
        startPlacing,
        exitPlacingMode,
        performPlacement,
        placeRect,
        placeCircle,
        placeText,
        placeDevice
    }
}